package com.boot.netty.utils;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public abstract class ChannelUtils {

    public static Channel connect(String host, int port, ChannelHandler handler) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast("toServer handler", handler);
                    }
                });

        try {
            ChannelFuture future = bootstrap.connect(host, port).sync();
            Channel res = future.isSuccess() ? future.channel() : null;
            return res;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
}
